package com.mew.lobby.handler.chat;

import com.alibaba.fastjson.JSON;
import com.mew.common.dc.redis.UserProfileRedisService;
import com.mew.common.enm.GoldProcessType;
import com.mew.common.enm.ZbmType;
import com.mew.common.entity.user.Profile;
import com.mew.common.entity.user.User;
import com.mew.common.exception.ResponseCode;
import com.mew.common.rest.LongMessage;
import com.mew.common.rest.StringMessage;
import com.mew.common.rest.bo.MewSession;
import com.mew.lobby.annotation.LobbyHandler;
import com.mew.lobby.message.response.ChatInfoResponseMessage;
import com.mew.lobby.net.LobbyHandlerMapCmdType;
import com.mew.lobby.net.MewHandler;
import com.mew.lobby.provide.ServerRegisterFeignService;
import com.mew.lobby.provide.UserFeignService;
import com.zebra.common.ZbmAreaType;
import com.zebra.common.ZbmMessage;
import com.zebra.remoting.protocol.ZebraCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**发送聊天消息
 * @author dylin
 * @create 2021/7/13
 */
@Service
@Slf4j
@LobbyHandler(LobbyHandlerMapCmdType.ChatSendInfo)
public class SendInfoHandler implements MewHandler<StringMessage> {
    @Autowired
    private UserProfileRedisService profileService;
    @Autowired
    private ServerRegisterFeignService serverRegisterFeignService;
    @Autowired
    private UserFeignService userFeignService;

    @Override
    public void handle(ZebraCommand<StringMessage> zebraCommand, MewSession session) {
        String info = zebraCommand.getRequest().getS();
        if(null==info&&info.isEmpty()){
            zebraCommand.sendFailureCode(ResponseCode.ParamInvalid.code());
            return;
        }
        long userid = zebraCommand.getUserId();
        User user = profileService.getRedisUserById(userid);
        if(user==null){
            zebraCommand.sendFailureCode(ResponseCode.LoginUn.code());
            return;
        }
        ChatInfoResponseMessage message = ChatInfoResponseMessage.builder()
                .userId(userid)
                .headPath(user.getHeadPath())
                .nickName(user.getNickname())
                .info(info)
                .build();
        serverRegisterFeignService.zbmCommon(ZbmMessage.builder()
                .zbmType(ZbmType.ChatInfo.code())
                .zbmArea(ZbmAreaType.Global.code())
                .msgJson(JSON.toJSONString(message))
                .build());
        // 收钱
        Profile profile = userFeignService.addGold(userid, -200l, GoldProcessType.ChatSendInfo.code());
        zebraCommand.sendMessage(LongMessage.builder().l(profile.getGoldNumber()).build());
    }
}
